<template>
    <n-drawer class="goods-container" :show="active" :width="width" :mask-closable="false" @update:show="(flag:boolean) => (active = flag)">
        <n-drawer-content :native-scrollbar="false" title="编辑" closable>
            <n-form :model="model" :rules="rules" ref="formRef">
                <n-grid :cols="24" :x-gap="24">
                    <n-form-item-gi :span="14" label="商品名称" path="Name">
                        <n-input placeholder="请填写商品名称" v-model:value="model.Name" maxlength="32" show-count clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="14" label="商品描述" path="Description">
                        <n-input placeholder="请填写商品描述" v-model:value="model.Description" type="textarea" show-count clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="24" label="轮播图" path="Slideshow">
                        <n-space vertical justify="center" :style="{ textAlign: 'center', width: '100%' }">
                            <n-card>
                                <template v-if="model.Slideshow && Array.isArray(model.Slideshow)">
                                    <div class="imgs">
                                        <n-image v-for="item in model.Slideshow" :width="width - 128" :height="((width - 128) / 5) * 3" object-fit="cover" :src="item" />
                                    </div>
                                </template>
                                <n-icon v-else size="128">
                                    <CloudUploadRound />
                                </n-icon>
                            </n-card>
                            <ButtonUploads v-model:value="model.Slideshow" type="Image" accept="image/png,image/jpeg,image/webp" title="上传轮播图" />
                        </n-space>
                    </n-form-item-gi>
                    <n-form-item-gi :span="24" label="详情图" path="DetailImg">
                        <n-space vertical justify="center" :style="{ textAlign: 'center', width: '100%' }">
                            <n-card>
                                <template v-if="model.DetailImg && Array.isArray(model.DetailImg)">
                                    <div class="imgs">
                                        <n-image v-for="item in model.DetailImg" :width="width - 128" :height="((width - 128) / 5) * 3" object-fit="cover" :src="item" />
                                    </div>
                                </template>
                                <n-icon v-else size="128">
                                    <CloudUploadRound />
                                </n-icon>
                            </n-card>
                            <ButtonUploads v-model:value="model.DetailImg" type="Image" accept="image/png,image/jpeg,image/webp" title="上传详情图" />
                        </n-space>
                    </n-form-item-gi>
                    <n-form-item-gi :span="12" label="颜色分类" path="Color">
                        <n-input placeholder="请填写颜色分类" v-model:value="model.Color" type="text" show-count clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="12" label="尺寸" path="Size">
                        <n-input placeholder="请填写尺寸" v-model:value="model.Size" type="text" show-count clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="12" label="库存" path="Stock">
                        <n-input placeholder="请填写库存" v-model:value="model.Stock" type="number" clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="12" label="商品售价" path="Price">
                        <n-input placeholder="请填写商品售价" v-model:value="model.Price" type="number" clearable />
                    </n-form-item-gi>
                    <!-- <n-form-item-gi :span="24" label="商品详情" path="price">
                        <div class="quill-container">
                            <quill-editor ref="quillRef" :toolbar="toolbarOptions" theme="snow"></quill-editor>
                        </div>
                    </n-form-item-gi> -->
                    <!-- <n-form-item-gi :span="4" label="商品状态" path="status">
                        <n-switch v-model:value="model.status" :round="false">
                            <template #checked>上架</template>
                            <template #unchecked>下架</template>
                        </n-switch>
                    </n-form-item-gi> -->
                    <!-- <n-form-item-gi :span="24" label="员工角色" path="roles">
                        <n-checkbox-group v-model:value="model.roles">
                            <n-space>
                                <n-checkbox v-for="r in UserRoleOpts" :value="r.value" :label="r.label" />
                            </n-space>
                        </n-checkbox-group>
                    </n-form-item-gi> -->
                </n-grid>
            </n-form>
            <template #footer>
                <n-space justify="end">
                    <n-button type="tertiary" :disabled="loading" @click="() => (active = false)">
                        <template #icon>
                            <n-icon :component="CloseRound" />
                        </template>
                        关闭
                    </n-button>
                    <n-button :disabled="loading" @click="execReset">
                        <template #icon>
                            <n-icon :component="RestoreRound" />
                        </template>
                        重置
                    </n-button>
                    <n-button type="primary" :loading="loading" @click="execSave">
                        <template #icon>
                            <n-icon :component="CheckRound" />
                        </template>
                        提交保存
                    </n-button>
                </n-space>
            </template>
        </n-drawer-content>
    </n-drawer>
</template>

<script lang="ts" setup>
import { computed, ref, shallowRef, onBeforeMount, onBeforeUnmount } from 'vue'
import { CloseRound, CheckRound, RestoreRound } from '@vicons/material'
import ButtonUploads from '@/comp/func/ButtonUploads.vue'
import { Http } from '@/libs'
import { UserRoleOpts } from '@/libs/enum'
import { useStore } from '@/store'

import District from '@/comp/func/District.vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'

const store = useStore()
const width = computed(() => Math.max(store.state.browser.innerWidth * 0.4, 640))

const { $notification: notification } = window

const loading = ref(false)

const prop = defineProps({
    show: {
        type: Boolean,
        required: true,
    },
    item: {
        type: Object,
        default: {},
    },
})

const tip = ref<string>((prop.item.areas || []).map((x: any) => x.name).join(' '))

const emit = defineEmits(['update:show', 'refresh'])

const active = computed({
    get: () => prop.show,
    set: val => emit('update:show', val),
})

const formRef = ref<any>(null)

const model = ref<any>({})

const rules = {
    // roles: {
    //     type: 'array',
    //     required: true,
    //     trigger: 'change',
    //     message: '请选择员工角色',
    // },
    Name: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请填写商品名称',
    },
    Description: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请填写商品描述',
    },
    Price: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请填写商品售价',
    },
}
const execReset = () => {
    if (!prop.item.ID) {
        model.value = {
            Name: '',
            Description: '',
            Color: '',
            Size: '',
            Stock: 100,
            Price: 0,
            Slideshow: [],
            DetailImg: [],
        }
        return
    }
    model.value = {
        ...prop.item,
        Price: prop.item.Price.toFixed(2),
    }
    console.log('model', model.value)
}
const quillRef = ref<any>(null)

const execSave = (e: Event) => {
    if (quillRef.value && quillRef.value.getHTML) {
        model.value.goodsDetail = quillRef.value.getHTML()
    }
    e.preventDefault()
    formRef.value.validate((errors: any[]) => {
        if (!errors) {
            loading.value = true
            if(model.value.ID){
                model.value.ID = String(model.value.ID)
            }
            Http.post('/ops/biz/gps/goods/save', {
                ...model.value,
                Price: Number(model.value.Price),
                detail_img: model.value.DetailImg,
            }).then(resp => {
                if (resp.stat.err > 0) {
                    loading.value = false
                    return
                }
                emit('refresh', {})
                notification.success({
                    duration: 1500,
                    title: '操作成功',
                    content: '您已成功保存商品信息',
                })
                setTimeout(() => {
                    loading.value = false
                    emit('update:show', false)
                }, 200)
            })
        } else {
            let msgs = errors.map(err => err[0].message)
            notification.error({
                duration: 1500,
                title: '请填写完整内容',
                description: '当前表单存在以下问题，请处理后提交',
                content: msgs.join('\n'),
            })
        }
    })
}

const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'], // toggled buttons
    ['blockquote', 'code-block'],
    ['image'],

    [{ header: 1 }, { header: 2 }], // custom button values
    [{ list: 'ordered' }, { list: 'bullet' }, { list: 'check' }],
    [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
    [{ indent: '-1' }, { indent: '+1' }], // outdent/indent

    [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
    [{ header: [1, 2, 3, 4, 5, 6, false] }],

    [{ color: [] }, { background: [] }], // dropdown with defaults from theme
    [{ font: [] }],
    [{ align: [] }],
]

onBeforeMount(() => {
    execReset()
})
</script>
<style>
.imgs {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 10px;
}
.imgs .n-image {
    cursor: pointer;
    width: 200px;
}
.imgs .n-image img {
    width: 200px;
    object-fit: contain !important;
}
.quill-container {
    width: 100%;
    height: 400px;
    margin-bottom: 20px;
}
.goods-container .ql-editor img {
    width: 100%;
    object-fit: contain !important;
}
</style>
